package com.ahdy.service.impl;

import com.ahdy.entity.EmergencyContact;
import com.ahdy.mapper.EmergencyContactMapper;
import com.ahdy.service.EmergencyContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 紧急联系人服务实现类
 */
@Service
public class EmergencyContactServiceImpl implements EmergencyContactService {

    @Autowired
    private EmergencyContactMapper emergencyContactMapper;

    @Override
    @Transactional
    public Integer addEmergencyContact(EmergencyContact contact) {
        // 如果设置为主要联系人，需要将同一老人的其他联系人设置为非主要
        if (Boolean.TRUE.equals(contact.getIsPrimary())) {
            EmergencyContact primaryContact = emergencyContactMapper.findPrimaryByElderlyId(contact.getElderlyId());
            if (primaryContact != null) {
                primaryContact.setIsPrimary(false);
                emergencyContactMapper.update(primaryContact);
            }
        }
        emergencyContactMapper.insert(contact);
        return contact.getId();
    }

    @Override
    @Transactional
    public int updateEmergencyContact(EmergencyContact contact) {
        // 如果设置为主要联系人，需要将同一老人的其他联系人设置为非主要
        if (Boolean.TRUE.equals(contact.getIsPrimary())) {
            EmergencyContact primaryContact = emergencyContactMapper.findPrimaryByElderlyId(contact.getElderlyId());
            if (primaryContact != null && !primaryContact.getId().equals(contact.getId())) {
                primaryContact.setIsPrimary(false);
                emergencyContactMapper.update(primaryContact);
            }
        }
        return emergencyContactMapper.update(contact);
    }

    @Override
    @Transactional
    public int deleteEmergencyContact(Integer id) {
        return emergencyContactMapper.deleteById(id);
    }

    @Override
    public EmergencyContact getEmergencyContactById(Integer id) {
        return emergencyContactMapper.findById(id);
    }

    @Override
    public List<EmergencyContact> getEmergencyContactsByElderlyId(Integer elderlyId) {
        return emergencyContactMapper.findByElderlyId(elderlyId);
    }

    @Override
    public EmergencyContact getPrimaryEmergencyContactByElderlyId(Integer elderlyId) {
        return emergencyContactMapper.findPrimaryByElderlyId(elderlyId);
    }

    @Override
    @Transactional
    public int deleteEmergencyContactsByElderlyId(Integer elderlyId) {
        return emergencyContactMapper.deleteByElderlyId(elderlyId);
    }

    @Override
    public List<EmergencyContact> getEmergencyContactsByElderlyIdAndPriority(Integer elderlyId, Integer maxPriority) {
        return emergencyContactMapper.findByElderlyIdAndPriority(elderlyId, maxPriority);
    }
}